﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using CE.Database;
using CE.Mail;
using CE.Global;
using CE.CarInsurance;
using CE.User;
using CE.Security;

public partial class QuoteDetails : MyLanguageBasePage
{
    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadManufactYearList();
            ddlCarMake.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarMake.ClientID + "','" + rfvCarMake.ClientID + "');");
            ddlCarYear.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarYear.ClientID + "','" + rfvCarYear.ClientID + "');");

            txtFirstName.Attributes.Add("onblur", "ShowValidationEffect('" + txtFirstName.ClientID + "','" + rfvName.ClientID + "');DefaultFirstName(this, event);");
            txtFirstName.Attributes.Add("onfocus", "ClearText(this, event);");
            txtEmail.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvtxtEmail.ClientID + "','" + rfvEmailValid.ClientID + "');DefaultEmail(this, event);");
            txtEmail.Attributes.Add("onfocus", "ClearText(this, event);");
            txtPhoneNum.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtPhoneNum.ClientID + "','" + rfvtxtPhoneNum.ClientID + "','" + revPhoneNo.ClientID + "');DefaultPhone(this, event);");
            txtPhoneNum.Attributes.Add("onfocus", "ClearText(this, event);");

            usrDOB.StartYear = General.GetUTCDateTime().Year - 75;
            usrDOB.EndYear = General.GetUTCDateTime().Year - 18;

            usrCommencementDate.StartYear = General.GetUTCDateTime().Year;
            usrCommencementDate.EndYear = General.GetUTCDateTime().Year + 1;

            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                divExisting.Visible = false;
                divLoggedin.Visible = true;
                btnLogout.Visible = true;
                btnSavedQuote.Visible = true;
                btnChangePassword.Visible = true;
                _userId = Convert.ToInt64(Session[General.UserId].ToString());

                ShowCustomerDetail(_userId);
            }
            else
            {
                divLoggedin.Visible = false;
                btnLogout.Visible = false;
                btnSavedQuote.Visible = false;
                btnChangePassword.Visible = false;
                GetCookies();
            }

            if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
            {
                Int64 _cecarid = Convert.ToInt64(Session[General.CarId]);
                Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                ShowCarAndPolicyDetail(_cecarid, _cepolicyid, 0);
            }


            if (Session["Language"] != null)
            {
                if (Session["Language"].ToString() == "th-TH")
                    hlnkAboutUs.NavigateUrl = "aboutus-th.aspx";
                else
                    hlnkAboutUs.NavigateUrl = "aboutus.aspx";
            }
            else
            {
                //english
                hlnkAboutUs.NavigateUrl = "aboutus.aspx";
            }

        }

    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            txtFirstName.Text = _profile.FirstName;
            ddlOccupation.Occupation = _profile.Occupation.ToString();
            ddlGender.Text = _profile.Gender.ToString();

            usrDOB.Day = _profile.DOB.Day;
            usrDOB.Month = _profile.DOB.Month;
            usrDOB.Year = _profile.DOB.Year;

            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtPhoneNum.Text = _contact.Mobile;

                txtEmail.Text = _contact.Email;
                txtEmail.IsReadOnly = true;

                SetPassword(false); //disable
            }
            _profile = null;
        }
    }

    private void SetPassword(bool bStatus)
    {
      txtEmail.Enabled = bStatus;
    }

    protected void btnApply_Click(object sender, EventArgs e)
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocMobileCarInquiryInsertUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@MobileCarInquiryId", 0);
        _spList.Add("@Name", txtFirstName.Text.Trim());
        _spList.Add("@EmailAddress", txtEmail.Text.Trim());
        _spList.Add("@PhoneNumber", txtPhoneNum.Text.Trim());//ddlMobile.SelectedItem.Text + " " + 
        _spList.Add("@CarMakeDescription", ddlCarMake.SelectedItem.Text);
        _spList.Add("@CarMakeCode", ddlCarMake.SelectedItem.Value);
        _spList.Add("@CarModelDescription", ddlCarModel.SelectedItem.Text);
        _spList.Add("@CarModelCode", ddlCarModel.SelectedItem.Value);
        _spList.Add("@CarYear", ddlCarYear.SelectedItem.Text);
       _spList.Add("@InsuranceClass", "");
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);

        SetCookies();

        if (_retValue > 0)
        {
            Int64 _userId = 0;
            
            if (Session[General.UserId] == null)
            {
                _userId = SaveNewCustomer();
            }
            else
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
                UpdateProfile(_userId, 0);
            }

            if (_userId > 0 && Save())
            {                
                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

                if (UpdateProfile(_userId, _carId) > 0)
                {
                    Response.Redirect("quote_result.aspx");
                }
            }
        }


        // }
    }

    private void LoadManufactYearList()
    {
        int _yearCount = 14;
        ddlCarYear.Items.Clear();
        int _startYear = General.GetUTCDateTime().Year - _yearCount;
        int _endYear = General.GetUTCDateTime().Year;

        for (int i = _endYear; i >= _startYear; i--)
        {
            ddlCarYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
        ddlCarYear.Items.Insert(0, new ListItem(Resources.CarInsurance.SelectCarYear, "-1"));
    }

    protected void ddlCarYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.Text == "-1")
        {
            ClearAllList();
        }
        else
        {
            GetCarMakeList(ddlCarYear.Text, ddlCarMake);
            if (ddlCarMake.Items.Count > 0)
            {
                ddlCarMake.SelectedIndex = 0;
                ddlCarMake_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        txtSumInsured.Text = "0";
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlCarModel.Items.Clear();
            ddlCarModel.Items.Add(new ListItem(Resources.CarInsurance.SelectCarModel, "-1"));

            txtSumInsured.Text = "0";

        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlCarYear.Text, ddlCarModel);
            if (ddlCarModel.Items.Count > 0)
            {
                ddlCarModel.SelectedIndex = 0;
                ddlCarModel_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.SelectCarMake, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlCarModel.Items.Clear();
        ddlCarModel.Items.Add(new ListItem(Resources.CarInsurance.SelectCarModel, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.DataSource = _dt;
                ddlList.DataTextField = "CarModelDisplay";
                ddlList.DataValueField = "CarModelDesc";
                ddlList.DataBind();
            }
        }
        ddlList.Items.Insert(0, new ListItem("- select your car model -", "-1"));
        _dt = null;
        _db = null;
    }

    protected void ddlCarModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlCarModel.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlCarModel.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlCarYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);

        }
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
            txtTextBox.Text = string.Format("{0:#,0}", _dt.Rows[0][0]);
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    protected void CheckPhoneNoServerValidation(object source, ServerValidateEventArgs args)
    {
        try
        {
            // Test whether the lenght of value is < 8 or Is Number Value.
            if (args.Value.Length < 8)
            {
                if (args.Value.Length == 0)
                    args.IsValid = true;
                else
                    args.IsValid = false;
            }
            else
            {

                args.IsValid = true;
            }
        }
        catch (Exception ex)
        {
            args.IsValid = false;
        }
    }

    private bool Save()
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        Int64 _refceuserid = 0;


        if (Session[General.CarId] != null)
        {
           _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
            if (Session[General.AgentId] != null)
            {
                _car.Info5 = "UPDATE";
            }
        }
        else
        {
            if (Session[General.AgentId] != null)
            {
                _car.Info4 = "NEW";
            }
        }
        if (_car == null)
        {
            _car = new CarDetailTH();
        }

        if (Session[CE.Global.General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
            _profile = _profiledb.GetProfile(_refceuserid);
            _contact = _contactdb.GetContact(_refceuserid);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;
                }
                _car.Info9 = _profile.Gender.ToString();
                _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy");
                _car.Info11 = _profile.Occupation.ToString();
                _car.Info12 = _profile.JobNature;
                _car.Info13 = _profile.MaritalStatus.ToString();
                _car.Info14 = "0"; 
                _car.Info15 = _profile.Salutation;
                _profile = null;
                _contact = null;
            }
        }
        _car.ManufactYear = Convert.ToInt32(ddlCarYear.Text);
        _car.CarMakeName = ddlCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
        string[] _tempDesc = ddlCarModel.Text.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;

        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = ddlVehicleType.Text;
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "210";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "220";
            }
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "320";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "340"; //Disabled, No Packages
            }
        }

        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlCarModel.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        _car.ViewedDetailId = 0;
        _car.CurrentStep = 1;
        _car.TotalStep = 4;
        _car.Info1 = "150";
        _carresult = _cardb.Insert(_car);
        _car = null;
        _cardb = null;
        if (_carresult > 0)
        {
            Session[CE.Global.General.CarId] = _carresult.ToString();
        }
        else
        {
            lblMessage.Text = "Insert error!";
        }
        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

            Int64 _carpolicyid = 0;

            if (Session[General.CarPolicyId] != null)
            {
                _carpolicyid = Convert.ToInt64(Session[General.CarPolicyId].ToString());
                _carpolicy.CECarPolicyId = _carpolicyid;
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info5 = "UPDATE";
                }
            }
            else
            {
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info4 = "NEW";
                }
            }

            lblMessage.Text = "";
            if (Session[General.AgentId] != null)
            {
                _carpolicy.Info2 = Session[General.AgentId].ToString();
                _carpolicy.Info3 = General.GetUTCDateTime().ToString();
            }
            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = Convert.ToInt32(ddlInsuranceClass.Text);
            _carpolicy.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _carpolicy.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text.Replace(",", ""));
            _carpolicy.ProvinceRegistration = "BKK";
            _carpolicy.UseOfVehicle = "N/A";
            _carpolicy.CoverageCommenceDate = usrCommencementDate.GetDate(); 
            _carpolicy.IsRedPlate = false; 

            _carpolicy.IsAddAccMod = false; 
            _carpolicy.NCDPercent = Convert.ToInt32(ddlNCB.Text);            
            _carpolicy.IsClaimLastYear = false; 
            _carpolicy.IsCTPL = false; 
            _carpolicy.IsAddDriver = false;             
            _carpolicy.Deductible = 0; 
            _carpolicy.CurrentInsurer = "Others"; 
            _carpolicy.RefCEUserId = _refceuserid;           
            _carpolicy.ViewedDetailId = 0;
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _carpolicy.Info8 = "mobile";
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                Session[General.CarPolicyId] = _policyresult.ToString();
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            _carpolicy = null;
            _carpolicydb = null;
        }


        return _policyresult > 0;
    }

    private void ShowCarAndPolicyDetail(Int64 CarId, Int64 PolicyId, Int64 UserId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        _cardetail = _cardetaildb.GetCar(CarId, UserId);

        CarPolicy _carpolicy = new CarPolicy();
        CarPolicyDB _carpolicydb = new CarPolicyDB();
        _carpolicy = _carpolicydb.GetCarPolicy(CarId, PolicyId, UserId);

        if (_carpolicy != null && _cardetail != null)
        {
            SetProperty(_carpolicy, _cardetail);
        }

        _cardetail = null;
        _cardetaildb = null;

        _carpolicy = null;
        _carpolicydb = null;
    }

    private void SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail)
    {
        ddlInsuranceClass.Text = _CarPolicy.InsuranceType.ToString();
        ddlGarageType.Text = _CarPolicy.GarageType.ToString();
        LoadManufactYearList();

        ddlCarYear.Text = _CarDetail.ManufactYear.ToString();
        ddlCarYear_SelectedIndexChanged(null, null);
        ddlCarMake.Text = _CarDetail.CarMakeName;
        ddlCarMake_SelectedIndexChanged(null, null);
        string _tempDesc = _CarDetail.CarModelName + " " + _CarDetail.Body + " " + _CarDetail.CC + "cc " + _CarDetail.Door.ToString() + " doors";

        ddlCarModel.Text = _tempDesc;
        ddlCarModel_SelectedIndexChanged(null, null);

        ddlNCB.Text = _CarPolicy.NCDPercent.ToString();

        txtGroupNo.Text = _CarDetail.GroupNo.ToString();
        lblCarVehicleType.Text = _CarDetail.Info2;
        txtSumInsured.Text = _CarPolicy.SumInsured.ToString();

        usrCommencementDate.Day = _CarPolicy.CoverageCommenceDate.Day;
        usrCommencementDate.Month = _CarPolicy.CoverageCommenceDate.Month;
        usrCommencementDate.Year = _CarPolicy.CoverageCommenceDate.Year;
        
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        string _redirectUrl = "logout.aspx";
        Response.Redirect(_redirectUrl);
    }

    protected void btnChangePassword_Click(object sender, EventArgs e)
    {
        string _redirectUrl = "ChangePassword.aspx";
        Response.Redirect(_redirectUrl);
    }

    protected void btnSavedQuote_Click(object sender, EventArgs e)
    {
        string _redirectUrl = "ViewResultHistory.aspx";
        Response.Redirect(_redirectUrl);
    }

    protected void ddlInsuranceClass_SelectedIndexChange(object sender, EventArgs e)
    {
        if (ddlInsuranceClass.SelectedItem.Text == "Class 3")
        {
            ddlGarageType.Visible = false;
            rfvGarageType.Visible = false;
        }
        else
        {
            ddlGarageType.Visible = true;
            rfvGarageType.Visible = true;
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                _profile.FirstName = txtFirstName.Text;
                _profile.SurName = ""; 
                _profile.DOB = usrDOB.GetDate();
                _profile.Gender = Convert.ToChar(ddlGender.Text);

                _profile.MaritalStatus = -1;
                _profile.JobNature = "";
                _profile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                _profile.YearDriveSg = 0;
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtPhoneNum.Text;
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
            
                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtPhoneNum.Text;//ddlMobile.Text + 
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";                   
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        bool _isEmailExist = false;
        divEmail.Visible = false;

        Account _useraccount = new Account();
        AccountDB _useraccountdb = new AccountDB();

        Profile _userprofile = new Profile();
        ProfileDB _userprofiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        if (_useraccountdb.IsAlreadyExist(txtEmail.Text.Trim(), Convert.ToInt32(CE.Global.General.CEUserType.Customer)))
        {
            _isEmailExist = true;
            _useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), 400);

            if (_useraccount != null && _useraccount.CEID > 0)
            {
                _contact = _contactdb.GetContact(_useraccount.CEID);
                if (_contact.Mobile == txtPhoneNum.Text.Trim())//ddlMobile.Text + 
                {
                    UpdateProfile(_useraccount.CEID, 0);

                    _profile = _profiledb.GetProfile(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                    _retVal = _useraccount.CEID;
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "validationError";
                    divEmail.Visible = true;
                    _retVal = 0;
                }
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "validationError";
                divEmail.Visible = true;
                _retVal = 0;
            }
        }

        if (_retVal == 0 && _isEmailExist == false)
        {
            long _result = -1;
           _useraccount.Email = txtEmail.Text.ToLower();
            string _authcode = txtPhoneNum.Text;            
            _useraccount.AuthCode = _authcode;

            _useraccount.UserId = "CEUSERAUTOIDMOBILECI";
            _useraccount.UserTypeId = Convert.ToInt32(CE.Global.General.CEUserType.Customer);
            _useraccount.IsAcceptTC = false;
            _useraccount.Status = true;
            _useraccount.RefCEUserID = -1;

            _result = _useraccountdb.Insert(_useraccount);
            _useraccount.CEID = _result;
            _retVal = _useraccount.CEID;

            if (_result > 0)
            {
                _userprofile.Salutation = ""; 
                _userprofile.FirstName = Server.HtmlEncode(txtFirstName.Text);
                _userprofile.SurName = "";

                DateTime _dtDOB = new DateTime(1900, 1, 1);
                _userprofile.DOB = _dtDOB;

                _userprofile.DOB = usrDOB.GetDate();
                _userprofile.Gender = Convert.ToChar(ddlGender.Text);

               _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                _userprofile.Status = "Complete";
                _userprofile.RefCEUserId = _useraccount.CEID;
                _userprofile.IsAcceptTC = true;
                _result = _userprofiledb.Insert(_userprofile);

                _contact.Email = _useraccount.Email;
                _contact.Mobile = txtPhoneNum.Text;

                _contact.Status = true;
                _contact.RefCEUserId = _useraccount.CEID;
                _result = _contactdb.Insert(_contact);

                if (_result > 0)
                {
                    SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    if (_userprofile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _userprofile.SurName;
                    }

                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    //SendMailToUser(_useraccount.Email, Session[CE.Global.General.UserName].ToString(), _contact.Mobile);
                }

            }
        }

        return _retVal;
        #endregion
    }

    protected void rdoExistingYes_Click(object sender, EventArgs e)
    {
        Response.Redirect("login.aspx");
    }

    protected void rdoExistingYes_CheckedChanged(object sender, EventArgs e)
    {
        Response.Redirect("login.aspx");
    }

    #region login existing user

    protected void btnPasswordClose_Click(object sender, EventArgs e)
    {
        inputLoginCount.Value = "0";

        string _redirectUrl = "~/quote.aspx";
        Response.Redirect(_redirectUrl);
    }

    protected void imgbtnLogin_Click(object sender, EventArgs e)
    {
        if (AutoLogin(100))
        {
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());

            }

            Int64 _carId = 0;

            if (Session[General.CarId] != null)
            {
                _carId = Convert.ToInt64(Session[General.CarId].ToString());
            }
            else
            {
                //Response.Redirect("carandpolicy_details.aspx");
                string _redirectUrl = "~/quote.aspx";
                Response.Redirect(_redirectUrl);
            }

            if (_userId > 0)
            {
                inputLoginHide.Value = "1";

                //update RefIds
                CarDetailTHDB cardb = new CarDetailTHDB();
                cardb.UpdateCarDetailPolicy(_carId, _userId);

                //btnNext.Enabled = true;
                //divPassword.Visible = false;
                //vsCarProfile.Visible = false;
                //divNewErrorMessage.Visible = false;

                mpePassword.Hide();
                divExisting.Visible = false;
                divLoggedin.Visible = true;
                //ShowCustomerDetail(_userId);

                inputLoginCount.Value = "0";

                //this.Page_Load(this, null);
                //Response.Redirect("profile.aspx");

            }

        }
        else
        {

            Int32 logincount = Convert.ToInt32(inputLoginCount.Value.Trim());
            inputLoginCount.Value = (logincount + 1).ToString();

            if (logincount == 2)
            {
                inputHideSignal.Value = "1";
            }
            else if (logincount >= 3)
            {
                this.btnPasswordClose_Click(this, null);
            }
            else
            {
                mpePassword.Show();
            }
        }

    }

    private bool AutoLogin(int LoginType)
    {
        bool isLoggedin = false;
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account

        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.General.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);

                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        isLoggedin = true;

                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        lblEmailMessage.Visible = false;
                        GetUserInformation(_account);
                        SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;                        
                    }
                    else
                    {
                        lblEmailMessage.Visible = true;
                        lblEmailMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblEmailMessage.Visible = true;
                    lblEmailMessage.Text = Resources.CarInsurance.EmailPasswordIncorrect;//"Email address or password is incorrect.";
                }
            }
            else
            {
                string _redirectUrl = "usermessage.aspx";
                Session["UMMSG"] = "UM,1993";

                Response.Redirect(_redirectUrl);


            }
        }
        else
        {
            lblEmailMessage.Visible = true;
            lblEmailMessage.Text = Resources.CarInsurance.EmailPasswordIncorrect;
        }

        return isLoggedin;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;          
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = General.GetUTCDateTime();
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;
        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName) + " " + Server.HtmlDecode(_profile.FirstName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    private void SetCookies()
    {
        try
        {
            HttpCookie _cookie = new HttpCookie("GGMobile_Quote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(txtFirstName.Text, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(txtEmail.Text, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(txtPhoneNum.Text, true));//ddlMobile.Text + 
            _cookie.Values.Add("CustomerDOB", MySecurity.Encrypt(usrDOB.GetDate().ToString("dd/MMM/yyyy"), true));
            _cookie.Values.Add("CustomerOccupation", ddlOccupation.GetOccupation());
            _cookie.Values.Add("CustomerGender", MySecurity.Encrypt(ddlGender.Text, true));
            _cookie.Values.Add("CustomerInsuranceType", ddlInsuranceClass.Text);
            _cookie.Values.Add("CustomerGarageType", ddlGarageType.Text);
            _cookie.Values.Add("CustomerNCD", ddlNCB.Text);
            _cookie.Values.Add("CustomerCarYear", ddlCarYear.Text);
            _cookie.Values.Add("CustomerCarMake", ddlCarMake.Text);
            _cookie.Values.Add("CustomerCarModel", ddlCarModel.Text);
            _cookie.Expires.AddYears(1);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGMobile_Quote");
            if (_cookie != null)
            {
                txtFirstName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);

                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtPhoneNum.Text = _mobile;

                DateTime _dob = Convert.ToDateTime(MySecurity.Decrypt(_cookie.Values.Get("CustomerDOB"),true));
                usrDOB.Day = _dob.Day;
                usrDOB.Month = _dob.Month;
                usrDOB.Year = _dob.Year;

                ddlOccupation.Occupation = _cookie.Values.Get("CustomerOccupation");
                ddlGender.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerGender"),true);

                if (Session[General.CarPolicyId] == null && Session[General.CarId] == null)
                {
                    ddlInsuranceClass.Text = _cookie.Values.Get("CustomerInsuranceType");
                    ddlInsuranceClass_SelectedIndexChange(null, null);

                    if (ddlGarageType.Visible)
                    {
                        ddlGarageType.Text = _cookie.Values.Get("CustomerGarageType");
                    }

                    ddlNCB.Text = _cookie.Values.Get("CustomerNCD");
                    ddlCarYear.Text = _cookie.Values.Get("CustomerCarYear");
                    ddlCarYear_SelectedIndexChanged(null, null);

                    ddlCarMake.Text = _cookie.Values.Get("CustomerCarMake");
                    ddlCarMake_SelectedIndexChanged(null, null);

                    ddlCarModel.Text = _cookie.Values.Get("CustomerCarModel");
                    ddlCarModel_SelectedIndexChanged(null, null);
                }
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.TH.UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            _retValue = false;
        }
        return _retValue;
    }

    #endregion
}
